package order

import (
	"context"

	"entgo.io/ent/dialect/sql"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/pancakebotorder"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/predicate"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPancakebotOrderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPancakebotOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPancakebotOrderListLogic {
	return &GetPancakebotOrderListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetPancakebotOrderListLogic) GetPancakebotOrderList(in *pancakebot.PancakebotOrderListReq) (*pancakebot.PancakebotOrderListResp, error) {
	// 构建查询条件
	var predicates []predicate.PancakebotOrder

	// 用户ID过滤
	if in.UserId != nil {
		predicates = append(predicates, pancakebotorder.UserIDEQ(*in.UserId))
	}

	// 设备ID过滤
	if in.DeviceId != nil {
		predicates = append(predicates, pancakebotorder.DeviceIDEQ(*in.DeviceId))
	}

	// 套餐名称过滤(模糊查询)
	if in.ComboName != nil {
		predicates = append(predicates, pancakebotorder.ComboNameContains(*in.ComboName))
	}

	// 支付状态过滤
	if in.PayStatus != nil {
		predicates = append(predicates, pancakebotorder.PayStatusEQ(*in.PayStatus))
	}

	// 支付渠道过滤
	if in.PayChannelCode != nil {
		predicates = append(predicates, pancakebotorder.PayChannelCodeEQ(*in.PayChannelCode))
	}

	// 查询总数
	count, err := l.svcCtx.DB.PancakebotOrder.Query().
		Where(predicates...).
		Count(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 查询订单列表(分页)
	orders, err := l.svcCtx.DB.PancakebotOrder.Query().
		Where(predicates...).
		Limit(int(in.PageSize)).
		Offset(int((in.Page - 1) * in.PageSize)).
		Order(pancakebotorder.ByCreatedAt(sql.OrderDesc())). // 按创建时间降序
		All(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 构建响应
	resp := &pancakebot.PancakebotOrderListResp{
		Total: uint64(count),
		Data:  make([]*pancakebot.PancakebotOrderInfo, 0, len(orders)),
	}

	// 转换数据
	for _, order := range orders {
		createdAt := order.CreatedAt.UnixMilli()
		updatedAt := order.UpdatedAt.UnixMilli()
		price := float32(order.Price)

		orderInfo := &pancakebot.PancakebotOrderInfo{
			Id:              &order.ID,
			CreatedAt:       &createdAt,
			UpdatedAt:       &updatedAt,
			UserId:          &order.UserID,
			DeviceId:        &order.DeviceID,
			ComboId:         &order.ComboID,
			ComboName:       &order.ComboName,
			ComboIngredient: []uint64{}, // 配料信息
			Price:           &price,

			PayStatus: &order.PayStatus,
		}

		// 设置可选字段
		if order.OutletNo != nil {
			outletNo := int64(*order.OutletNo)
			orderInfo.OutletNo = &outletNo
		}

		if order.OutletTime != nil {
			outletTime := order.OutletTime.UnixMilli()
			orderInfo.OutletTime = &outletTime
		}

		if order.PayOrderId != 0 {
			orderInfo.PayOrderId = &order.PayOrderId
		}

		if !order.PayTime.IsZero() {
			payTime := order.PayTime.UnixMilli()
			orderInfo.PayTime = &payTime
		}

		if order.PayChannelCode != "" {
			orderInfo.PayChannelCode = &order.PayChannelCode
		}

		if order.PayRefundID != 0 {
			orderInfo.PayRefundId = &order.PayRefundID
		}

		if order.RefundPrice != 0 {
			orderInfo.RefundPrice = &order.RefundPrice
		}

		if !order.RefundTime.IsZero() {
			refundTime := order.RefundTime.UnixMilli()
			orderInfo.RefundTime = &refundTime
		}

		resp.Data = append(resp.Data, orderInfo)
	}

	return resp, nil
}
